<script setup>
import HeaderNavTabarSvg from '@/components/HeaderNavTabarSvg/HeaderNavTabar.vue'
import { onLoad } from '@dcloudio/uni-app'
import approvalProcessState from '@/store/modules/approvalProcess'
import AuditApplicationSteps from '@/components/audit/function/auditApplicationSteps.vue'
import DescriptionAttachment from '@/components/audit/function/descriptionAttachment.vue'
import { computed, ref, watch } from 'vue'
import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
import customParseFormat from 'dayjs/plugin/customParseFormat'
import { attendanceApplyApi } from '@/api/attendance'
import { getUserProfile } from '@/api/system/user'
import { calculateTotalWorkHours } from '@/utils/date'
import { isObjectValuesNotEmpty } from '@/utils/objIsnull.js'

dayjs.extend(isBetween)
dayjs.extend(customParseFormat)
const title = '请假'
const typePicker = ref(true)
const leaceTypeRef = ref(null)
const leaceList = ref({
  depName: '',
  leaceType: '',
})
// 新疆
let userIdAttendabceArr = [82] // 罗平
// 郑州
let deptAttendabce = [8253, 6707, 6708, 8254, 6701, 6702, 6703, 6704, 8255, 8256, 8242] // 8242郑州部门id
// 郑州郑州绿地之窗景峰座1号楼打卡
let cxyuserIdAttendabceArr = [147, 106, 108, 99, 163, 97] // 郑州郑州绿地之窗景峰座1号楼打卡
let deptAttendabceZhenZhou = ref(null) // 8242郑州部门id
let userIdAttendabce = ref(null) // 用户

//时间选择器功能
const bukaData = ref({
  datetimeValue: '',
  datetimeValue2: '',
})
const datetimePicker = ref(null)
const datetimePicker2 = ref(null)
// const time = ref(Date.now()); // 初始化为当前时间戳
const time = ref(JSON.stringify(dayjs()))
// 打开选择器
const toggle = (type) => {
  //日期一
  if (!leaceList.value.leaceType) {
    uni.showToast({
      title: '请选择请假类型',
      icon: 'error',
    })
  } else {
    time.value = Date.now() // 打开选择器显示当前最新时间
    datetimePicker.value.open()
  }
}
const toggle2 = (type) => {
  //日期二
  if (!leaceList.value.leaceType) {
    uni.showToast({
      title: '请选择请假类型',
      icon: 'error',
    })
  } else {
    if (bukaData.value.datetimeValue) {
      datetimePicker2.value.open()
    } else {
      uni.showToast({
        title: '请先选择开始时间',
        icon: 'none',
      })
    }
  }
}

const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}
let timeChuo = ref(0)
const confirm = (obj) => {
  //开始时间
  if (typePicker.value) {
    bukaData.value.datetimeValue = dayjs(obj.value).format('YYYY-MM-DD HH:mm:ss')
    let newTime = new Date(bukaData.value.datetimeValue)
    timeChuo.value = newTime.getTime()
  } else {
    startDate.value = dayjs(obj.value).format('YYYY-MM-DD')
    bukaData.value.datetimeValue = formatDateTime(startDate.value, startAMPM.value, 'start')
    let newTime = new Date(bukaData.value.datetimeValue)
    timeChuo.value = newTime.getTime()
  }
  if (timeChuo.value >= timeChuo2.value && timeChuo2.value != '' && timeChuo.value != '') {
    bukaData.value.datetimeValue = ''
    timeChuo.value = ''
    uni.showToast({
      title: '开始时间不能大于等于结束时间',
      duration: 2000,
      icon: 'none',
    })
    return false
  }
}

let timeChuo2 = ref(0)
const confirm2 = (obj) => {
  //结束时间
  if (typePicker.value) {
    bukaData.value.datetimeValue2 = dayjs(obj.value).format('YYYY-MM-DD HH:mm:ss')
    let newTime = new Date(bukaData.value.datetimeValue2)
    timeChuo2.value = newTime.getTime()
  } else {
    endDate.value = dayjs(obj.value).format('YYYY-MM-DD')
    bukaData.value.datetimeValue2 = formatDateTime(endDate.value, endAMPM.value, 'end')
    let newTime = new Date(bukaData.value.datetimeValue2)
    timeChuo2.value = newTime.getTime()
  }
  if (timeChuo2.value <= timeChuo.value && timeChuo.value != '') {
    bukaData.value.datetimeValue2 = ''
    timeChuo2.value = ''
    uni.showToast({
      title: '结束时间不能小于等于开始时间',
      duration: 2000,
      icon: 'none',
    })
    return false
  }
}

// 打开模态床
const toggleLeace = () => {
  leaceTypeRef.value.open() // 调用子组件的 show 方法
}
const leaceTypeColumns = [['年假', '事假', '病假', '调休假', '婚假', '产假', '陪产假', '其他']]
let attchment = ref(null)

const getDesignDrawingsEmit = (emit) => {
  attchment.value = emit
}

const leaceTypeConfirm = (e) => {
  leaceList.value.leaceType = e.value[0]
}
const userName = ref(null)
const deptId = ref(null)
const userId = ref(null)
const getUserProfileFn = async () => {
  let { code, data } = await getUserProfile()
  if (code === 200) {
    deptId.value = data.deptId
    userId.value = data.userId
    userName.value = data.nickName
    deptAttendabceZhenZhou.value = data.deptId
    userIdAttendabce.value = data.userId // 用户
  }
}

let ab = computed(() => {
  // 向上取整
  // return Math.ceil(
  //   calculateTotalWorkHours(bukaData.value.datetimeValue, bukaData.value.datetimeValue2),
  // )
  return calculateTotalWorkHours(
    bukaData.value.datetimeValue,
    bukaData.value.datetimeValue2,
    userIdAttendabce.value,
    deptAttendabceZhenZhou.value,
  )
})

// 判断数字(天数)是否为 0.5 的倍数
const isHalfMultiple = (num) => {
  return num % 0.5 === 0
}

const clickSave = async () => {
  const RequiredItemList = JSON.parse(JSON.stringify(bukaData.value))
  RequiredItemList.leaceType = leaceList.value.leaceType

  // true 小时 false 天
  if (bukaData.value.datetimeValue && bukaData.value.datetimeValue2) {
    if (
      new Date(bukaData.value.datetimeValue2).getTime() <=
      new Date(bukaData.value.datetimeValue).getTime()
    ) {
      uni.showToast({
        title: '结束时间不能小于等于开始时间',
        duration: 2000,
        icon: 'none',
      })
      return false
    }
  }
  if (isObjectValuesNotEmpty(RequiredItemList)) {
    let params = {
      deptId: deptId.value,
      userId: userId.value,
      type2: leaceList.value.leaceType,
      startTime: new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD HH:mm:ss'),
      endTime: new dayjs(bukaData.value.datetimeValue2).format('YYYY-MM-DD HH:mm:ss'),
      attchment: JSON.stringify(attchment.value),
      // duration: Math.ceil(
      //   calculateTotalWorkHours(bukaData.value.datetimeValue, bukaData.value.datetimeValue2),
      // ),
      duration: typePicker.value
        ? calculateTotalWorkHours(
            bukaData.value.datetimeValue,
            bukaData.value.datetimeValue2,
            userIdAttendabce.value,
            deptAttendabceZhenZhou.value,
          )
        : calculateLeaveDays(),
      type: '请假',
      ruleId: 'qingjia',
      approve: approvalProcessState.state.approvalProcess,
    }
    // console.log(params, 'params')
    let { code } = await attendanceApplyApi(params)
    if (code === 200) {
      uni.showToast({
        title: '提交成功',
        duration: 1500,
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack({
          url: '/pages/attendance/attendancePage',
        })
      }, 1000)
    }
  } else {
    uni.showToast({
      title: '请输入完整数据',
      icon: 'error',
    })
  }
}
const goHistoryView = () => {
  uni.navigateTo({
    url: '/components/TypeDefineModel?type=请假',
  })
}

watch(
  () => leaceList.value.leaceType,
  (val) => {
    if (val === '事假' || val === '病假' || val === '其他') {
      typePicker.value = true
    } else {
      typePicker.value = false
    }
  },
)

onLoad(async () => {
  await getUserProfileFn()
})

const leaveTypeIndex = ref(0) // 当前选中的请假类型索引
const leaveReason = ref('') // 请假事由

// 时间相关数据
// const startDate = ref(new Date().toISOString().split('T')[0]) // 默认今天
// const endDate = ref(new Date().toISOString().split('T')[0]) // 默认今天
const startDate = ref('') // 默认
const endDate = ref('') // 默认
const startAMPM = ref('AM') // 上午/下午
const endAMPM = ref('PM') // 上午/下午

// 控制日期选择器显示
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 开始时间上午下午选择
const startAMPMClick = (type) => {
  startAMPM.value = type
  bukaData.value.datetimeValue = formatDateTime(startDate.value, startAMPM.value, 'start')
}
// 结束时间上午下午选择
const endAMPMClick = (type) => {
  endAMPM.value = type
  bukaData.value.datetimeValue2 = formatDateTime(endDate.value, endAMPM.value, 'end')
}

// 格式化日期显示为 月/日
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return dateStr ? `${date.getMonth() + 1}/${date.getDate()}` : '请选择'
}

// 获取周几
const getWeek = (dateString) => {
  // 如果没有传入日期，则使用当前日期
  const date = dateString ? dayjs(dateString) : dayjs()
  const day = date.day()
  const week = ['日', '一', '二', '三', '四', '五', '六']
  return '星期' + week[day]
}

// 上午下午日期转换
const formatDateTime = (dateStr, period, type) => {
  // type: start开始日期 end结束日期
  if (period === 'AM' && type === 'start') {
    // 新疆
    if (userIdAttendabceArr.includes(userIdAttendabce.value)) {
      if (getWeek(dateStr) === '星期一') {
        return `${dateStr} 07:50:00`
      } else {
        return `${dateStr} 08:00:00`
      }
    } else if (deptAttendabce.includes(deptAttendabceZhenZhou.value)) {
      // 郑州
      if (getWeek(dateStr) === '星期一') {
        return `${dateStr} 07:50:00`
      } else {
        return `${dateStr} 08:30:00`
      }
    } else if (cxyuserIdAttendabceArr.includes(userIdAttendabce.value)) {
      // 郑州晨讯云
      if (getWeek(dateStr) === '星期一') {
        return `${dateStr} 07:50:00`
      } else {
        return `${dateStr} 09:00:00`
      }
    } else {
      if (getWeek(dateStr) === '星期一') {
        return `${dateStr} 07:50:00`
      } else {
        return `${dateStr} 08:00:00`
      }
    }
  } else if (period === 'AM' && type === 'end') {
    // 新疆
    if (userIdAttendabceArr.includes(userIdAttendabce.value)) {
      return `${dateStr} 12:30:00`
    } else if (deptAttendabce.includes(deptAttendabceZhenZhou.value)) {
      // 郑州
      return `${dateStr} 12:00:00`
    } else if (cxyuserIdAttendabceArr.includes(userIdAttendabce.value)) {
      return `${dateStr} 12:00:00`
    } else {
      return `${dateStr} 12:00:00`
    }
  } else if (period === 'PM' && type === 'start') {
    // 新疆
    if (userIdAttendabceArr.includes(userIdAttendabce.value)) {
      return `${dateStr} 14:30:00`
    } else if (deptAttendabce.includes(deptAttendabceZhenZhou.value)) {
      // 郑州
      return `${dateStr} 14:00:00`
    } else if (cxyuserIdAttendabceArr.includes(userIdAttendabce.value)) {
      return `${dateStr} 14:00:00`
    } else {
      return `${dateStr} 14:30:00`
    }
  } else if (period === 'PM' && type === 'end') {
    // 新疆
    if (userIdAttendabceArr.includes(userIdAttendabce.value)) {
      return `${dateStr} 19:00:00`
    } else if (deptAttendabce.includes(deptAttendabceZhenZhou.value)) {
      // 郑州
      return `${dateStr} 18:30:00`
    } else if (cxyuserIdAttendabceArr.includes(userIdAttendabce.value)) {
      return `${dateStr} 19:00:00`
    } else {
      return `${dateStr} 18:30:00`
    }
  }

  return dateStr // 如果没有 AM/PM，返回原日期
}

// 计算请假天数
const calculateLeaveDays = () => {
  const start = new Date(startDate.value)
  const end = new Date(endDate.value)

  // 处理开始日期晚于结束日期的情况
  if (start > end) return 0

  // 计算日期差（以整天为单位）
  const timeDiff = end.getTime() - start.getTime()
  const fullDays = Math.floor(timeDiff / (1000 * 3600 * 24))

  // 处理同一天的情况
  if (fullDays === 0) {
    if (startAMPM.value === 'AM' && endAMPM.value === 'PM') return 1
    if (startAMPM.value === 'AM' && endAMPM.value === 'AM') return 0.5
    if (startAMPM.value === 'PM' && endAMPM.value === 'PM') return 0.5
    return 0 // PM → AM
  }

  // 处理跨天情况
  let days = 0

  // 1. 计算开始日
  if (startAMPM.value === 'AM') {
    days += 1 // 开始日上午 → 算整天
  } else {
    days += 0.5 // 开始日下午 → 算半天
  }

  // 2. 计算结束日
  if (endAMPM.value === 'PM') {
    days += 1 // 结束日下午 → 算整天
  } else {
    days += 0.5 // 结束日上午 → 算半天
  }

  // 3. 计算中间完整日
  if (fullDays > 1) {
    days += fullDays - 1 // 减去开始和结束日
  }

  return days
}
</script>

<template>
  <view>
    <!--    请假  -->
    <HeaderNavTabarSvg :title="title">
      <image class="bukaSvg" src="/static/icon/auditSVG/buka.svg" @tap="goHistoryView"></image>
    </HeaderNavTabarSvg>
    <view class="picker-content">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">申请人</text>
        <view class="info-list-right">
          <view class="uni-input">{{ userName }}</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>

    <view class="picker-content" @tap="toggleLeace">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">请假类型</text>
        <view class="info-list-right">
          <view class="uni-input">{{ leaceList.leaceType }}</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>
    <uv-picker
      ref="leaceTypeRef"
      :columns="leaceTypeColumns"
      @confirm="leaceTypeConfirm"
    ></uv-picker>

    <view v-if="typePicker">
      <view :class="leaceList.leaceType ? '' : 'activePicker'" class="picker-content" @tap="toggle">
        <view class="measurement-info-list">
          <text class="info-list-left isrequired">开始时间</text>
          <view class="info-list-right">
            <view v-if="bukaData.datetimeValue" class="uni-input"
              >{{ bukaData.datetimeValue }}
            </view>
            <view v-else class="uni-input">请选择</view>
            <i class="iconfont icon-youjiantou"></i>
          </view>
        </view>
      </view>

      <view
        :class="leaceList.leaceType ? '' : 'activePicker'"
        class="picker-content"
        @tap="toggle2"
      >
        <view class="measurement-info-list">
          <text class="info-list-left isrequired">结束时间</text>
          <view class="info-list-right">
            <view v-if="bukaData.datetimeValue2" class="uni-input"
              >{{ bukaData.datetimeValue2 }}
            </view>
            <view v-else class="uni-input">请选择</view>
            <i class="iconfont icon-youjiantou"></i>
          </view>
        </view>
      </view>
    </view>
    <view v-else>
      <!-- 请假时间 -->
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">请假时间</text>
        <view class="time-range">
          <!-- 开始时间 -->
          <view :class="leaceList.leaceType ? '' : 'activePicker'" class="time-item" @tap="toggle">
            <text>{{ formatDate(startDate) }}</text>
            <view class="ampm-select">
              <text
                :class="['ampm-btn', startAMPM === 'AM' ? 'active' : '']"
                @click.stop="startAMPMClick('AM')"
                >上午
              </text>
              <text
                :class="['ampm-btn', startAMPM === 'PM' ? 'active' : '']"
                @click.stop="startAMPMClick('PM')"
                >下午
              </text>
            </view>
          </view>

          <text class="separator">至</text>

          <!-- 结束时间 -->
          <view :class="leaceList.leaceType ? '' : 'activePicker'" class="time-item" @tap="toggle2">
            <text>{{ formatDate(endDate) }}</text>
            <view class="ampm-select">
              <text
                :class="['ampm-btn', endAMPM === 'AM' ? 'active' : '']"
                @click.stop="endAMPMClick('AM')"
                >上午
              </text>
              <text
                :class="['ampm-btn', endAMPM === 'PM' ? 'active' : '']"
                @click.stop="endAMPMClick('PM')"
                >下午
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <uv-datetime-picker
      ref="datetimePicker"
      v-model="time"
      :formatter="formatter"
      :mode="typePicker ? 'datetime' : 'date'"
      @confirm="confirm"
    >
    </uv-datetime-picker>
    <uv-datetime-picker
      ref="datetimePicker2"
      v-model="time"
      :formatter="formatter"
      :mode="typePicker ? 'datetime' : 'date'"
      @confirm="confirm2"
    >
    </uv-datetime-picker>
    <view :class="leaceList.leaceType ? '' : 'activePicker'" class="picker-content">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">请假时长</text>
        <view class="info-list-right">
          <view
            v-if="bukaData.datetimeValue2 && bukaData.datetimeValue && typePicker"
            class="uni-input"
          >
            {{ ab }}
            <text>小时</text>
          </view>
          <view
            v-if="bukaData.datetimeValue2 && bukaData.datetimeValue && !typePicker"
            class="uni-input"
          >
            {{ calculateLeaveDays() }}
            <text>天</text>
          </view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>
    <!--    说明附件-->
    <DescriptionAttachment @getDesignDrawingsEmit="getDesignDrawingsEmit" />
    <!--    审批流程-->
    <AuditApplicationSteps :ruleId="'qingjia'" :time="ab" />
    <!--    底部占位符-->
    <view class="blank"></view>
    <!--    保存-->
    <view class="buttonContainer">
      <button class="buttonClass" @click="clickSave">提交</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.bukaSvg {
  width: 32rpx;
  height: 32rpx;
}

.buttonContainer {
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  align-items: center;
  padding: 16rpx;
  background-color: #fff;
}

.buttonClass {
  display: flex;
  width: 686rpx;
  height: 72rpx;
  justify-content: center;
  align-items: center;
  background: #165dff;
  border-radius: 16rpx;
  color: #fff;
  font-size: 32rpx;
  //margin-top: 40rpx;
  overflow: hidden;
}

.activePicker {
  color: #86909c !important;

  .info-list-left {
    color: #86909c !important;
  }
}

.blank {
  height: calc(72rpx + 32rpx + 20rpx);
}

.bukabanci {
  .info-content {
    color: #86909c !important;
  }

  .info-list-left {
    // @include font-color-auxiliary;
    color: #86909c !important;
  }
}

.textarea-box {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .textinfo-list {
    margin-top: 20rpx;
    width: 100%;
    height: 200rpx;
  }
}

.popup-content {
  background: #f7f8fa;

  .header-box {
    padding: 30rpx 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    p {
      color: #1d2129;
      font-size: 34rpx;
      font-weight: 500;
    }

    .module-image-ba {
      border-radius: 32rpx;
      background: #f2f3f5;
      width: 45rpx;
      height: 45rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .card-list {
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .list {
      box-shadow: 0 4rpx 16rpx 0 #0000000d;
      box-sizing: border-box;
      width: 100%;
      background: #fff;
      padding: 16rpx 24rpx;
      border-radius: 8rpx;
      margin-bottom: 10rpx;

      h4 {
        color: #1d2129;
        font-size: 32rpx;
        font-weight: 400;
      }

      p {
        color: #86909c;
        font-size: 24rpx;
        font-weight: 400;
        margin-top: 10rpx;
      }
    }
  }
}

.measurement-info-list {
  @include flex($align: center, $justify: space-between);
  padding: $spacing-row-base;
  background: #fff;
  margin-top: 16rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .info-list-right {
    @include flex($align: center);

    .info-content {
      @include textStyleBase;
      font-size: 34rpx;
    }

    .iconfont {
      margin-left: 16rpx;
      // @include font-color-auxiliary;
      color: $uni-fc-fu-lin;
    }
  }

  .unit {
    // @include font-color-auxiliary;
    color: $uni-fc-fu-lin;
  }
}

.header {
  padding: 30rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.picker {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.time-range {
  display: flex;
  align-items: center;
}

.time-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
}

.separator {
  margin: 0 20rpx;
  color: #999;
}

.ampm-select {
  display: flex;
  margin-top: 10rpx;
  background-color: #e6e6e6;
  border-radius: 6rpx;
  overflow: hidden;
}

.ampm-btn {
  padding: 6rpx 20rpx;
  font-size: 24rpx;
  color: #666;
}

.ampm-btn.active {
  background-color: #1890ff;
  color: #fff;
}

.value {
  font-size: 28rpx;
  color: #333;
}

.textarea-item {
  flex-direction: column;
  align-items: flex-start;
}

.textarea {
  width: 100%;
  height: 200rpx;
  margin-top: 20rpx;
  padding: 20rpx;
  background-color: #f7f7f7;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.submit-btn {
  margin: 40rpx auto;
  width: 90%;
  height: 80rpx;
  background-color: #1890ff;
  color: #fff;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  font-weight: 500;
}
</style>
